<?php
declare (strict_types=1);

namespace app\listener\notify;

use app\common\service\order\coupon_order\coupon\CouponOrderBuild;
use app\event\SupplierNotifySuccess;
use app\model\CouponOrder;
use app\model\CouponOrderHistory;
use app\model\CouponProductChannel;
use think\facade\Log;

class CouponButtFail
{
    /**
     * 只处理权益的
     * 事件监听处理
     * @param SupplierNotifySuccess $event
     * @return mixed
     */
    public function handle($event)
    {
        $couponOrder = $event->couponOrder;

        if ($couponOrder->serv_type != PRODUCT_COUPON_SERV) {
            return true;
        }

        if ($couponOrder->serv_type != PRODUCT_COUPON_SERV && $couponOrder->getAttr('type') != CouponOrder::TYPE_COUPON_SELF_EMPLOYED) {
            return true;
        }

        if ($couponOrder->status == CouponOrder::C_STATUS_RECHARGE_FAIL) {
            return true;
        }


        $histtoryQuoteId = CouponOrderHistory::query()
            ->where('order_id', $couponOrder->order_id)
            ->group('quote_id')
            ->column(['quote_id']);


        $histtoryQuoteId[] = $couponOrder->quote_id;

        if (empty($couponOrder->couponProductChannel)) {
            Log::error('错误id' . $couponOrder->quote_id);
            Log::error('错误的订单id' . $couponOrder->id);
        }

        $nextChannel = CouponProductChannel::query()
            ->where('product_id', $couponOrder->couponProductChannel->product_id)
            ->where('supplier_id', '<>', $couponOrder->couponProductChannel->supplier_id)
            ->order('cost_price', 'asc')->whereNotIn('id', $histtoryQuoteId)->find();

        if (!$nextChannel) {
            $this->refundStatus($couponOrder);
            return true;
        }
        //如果还有，其他渠道则轮训
        //更新表数据__进入等待区域
        $couponOrder->quote_id = $nextChannel->id;

        $newCouponOrder = new CouponOrder();
        $newCouponOrder->quote_id = $couponOrder->quote_id;
        $newCouponOrder->agent_id = $couponOrder->agent_id;

        $buildService = new CouponOrderBuild($newCouponOrder);

        //如果支付金额小于结算金额则不再进行轮训
        if ($couponOrder->pay_amount < $buildService->settle_price) {
            $this->refundStatus($couponOrder);
            return true;
        }

        //保存历史记录
        $cloneObj = clone $couponOrder;
        $arr = $cloneObj->hidden(
            [
                'ext_data',
            ]
        )->toArray();
        unset($arr['id']);
        $history = new CouponOrderHistory($arr);
        $history->save();

        $updateFormat = [
            'supplier_id' => $buildService->supplier_id,
            'settle_price' => $buildService->settle_price,
            'supplier_price' => $buildService->supplier_price,
            'profit' => $buildService->profit,
            'platform_profit' => $buildService->platform_profit,
            'quote_id' => $nextChannel->id,
            'origin_amount' => $buildService->origin_amount,
            'supplier_status' => CouponOrder::SUPPLIER_STATUS_WAIT, //等待提交
            'status' => CouponOrder::C_STATUS_NO_SUBMIT, //设置为未提交
        ];

        $couponOrder->where('id', $couponOrder->id)->update($updateFormat);

    }


    /**
     * 更新退款状态
     * @param $couponOrder
     * @return bool
     */
    public function refundStatus($couponOrder)
    {
        //退款
        $res = $couponOrder->where('id', $couponOrder->id)
            ->where('refund_status', CouponOrder::C_REFUND_STATUS_NO)
            ->update([
                'supplier_status' => CouponOrder::SUPPLIER_STATUS_FAIL,
                'status' => CouponOrder::C_STATUS_RECHARGE_FAIL,
                'refund_status' => CouponOrder::C_REFUND_STATUS_ING,
                'refund_amount' => $couponOrder->pay_amount,
            ]);

        return $res;
    }


}
